/********************************************************************
	File		: Texture.cpp
	Created		: 2011-2-25	23:04
	Author		: Wjl

	Desc		: This file is part of omiga 2d engine.
*********************************************************************/

#include "Texture.h"

Vis::Texture::Texture() : m_uiId(0)
{

}

Vis::Texture::~Texture()
{
	glDeleteTextures(1, &m_uiId);
}

void Vis::Texture::LoadTGAFile( const std::string& _fileName )
{
	FILE *fp;
	tga_texture_t *texinfo;
	tga_header_t header;

	fp = fopen (_fileName.c_str(), "rb");
	if (!fp)
	{
		fprintf (stderr, "error: couldn't open \"%s\"!\n", _fileName);
		return;
	}

	// read header 
	fread (&header, sizeof (tga_header_t), 1, fp);

	texinfo = (tga_texture_t *)malloc (sizeof (tga_texture_t));
	texinfo->width  = header.width;
	texinfo->height = header.height;

	switch (header.image_type)
	{ 
	case 2:  /* BGR 16-24-32 bits */
		texinfo->internalFormat= 4;
		texinfo->format=GL_RGBA;
		break;
	default:
		fprintf (stderr, "TGA format not supported\n");
		break;
	}
	fseek (fp, header.id_lenght, SEEK_CUR);

	// memory allocation 
	texinfo->texels = (char *)malloc (sizeof (char) *
		texinfo->width * texinfo->height * texinfo->internalFormat);

	if (!texinfo->texels)
	{
		free (texinfo);
		return;
	}

	// read image data 
	switch (header.image_type)
	{

	case 2:
		// uncompressed 16-24-32 bits 
		switch (header.pixel_depth)
		{
		case 16:
			//ReadTGA16bits (fp, texinfo);
			break;

		case 24:
			//ReadTGA24bits (fp, texinfo);
			break;

		case 32:
			{
				int i;

				for (i = 0; i <texinfo->width * texinfo->height  ; ++i)
				{
					/* read and convert BGRA to RGBA */

					texinfo->texels[((i) * texinfo->internalFormat) + 2] = (char)fgetc (fp);
					texinfo->texels[((i) * texinfo->internalFormat) + 1] = (char)fgetc (fp);
					texinfo->texels[((i) * texinfo->internalFormat) + 0] = (char)fgetc (fp);
					texinfo->texels[((i) * texinfo->internalFormat) + 3] = (char)fgetc (fp);
				}
			}
			break;
		}

		break;

	default:
		// image type is not correct 
		fprintf (stderr, "error: unknown TGA image type %i!\n", header.image_type);
		free (texinfo->texels);
		free (texinfo);
		texinfo = NULL;
		break;
	}

	fclose (fp);
	
	texinfo;
	if (texinfo && texinfo->texels)
	{
		// generate texture 
		glGenTextures (1, &texinfo->id);
		glBindTexture (GL_TEXTURE_2D, texinfo->id);

		// setup some parameters for texture filters and mipmapping 
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST/*_MIPMAP_LINEAR*/);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

		glTexImage2D (GL_TEXTURE_2D, 0, texinfo->internalFormat,
			texinfo->width, texinfo->height, 0, texinfo->format,
			GL_UNSIGNED_BYTE, texinfo->texels);

		m_uiId = texinfo->id;

		// OpenGL has its own copy of texture data 
		free (texinfo->texels);
		free (texinfo);
	}
}